package gold.digger;

import gold.vo.ListNode;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * Created by fanzhenyu02 on 2020/3/1.
 */
public class LC21 {


    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode[] lists = new ListNode[2];
        lists[0] = l1;
        lists[1] = l2;
        return mergeKLists(lists);
    }


    public ListNode mergeKLists(ListNode[] lists) {
        if (null == lists || lists.length <= 0) {
            return null;
        }

        if (lists.length == 1) {
            return lists[0];
        }

        List<Integer> arr = new ArrayList<>();

        for (ListNode li : lists) {
            while (null != li) {
                arr.add(li.val);
                li = li.next;
            }
        }

        if (arr.size() <= 0) {
            return null;
        }

        arr.sort(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1 - o2;
            }
        });

        ListNode re = new ListNode(arr.get(0));
        ListNode head = re;
        for (int i = 1; i < arr.size(); ++i) {
            re.next = new ListNode(arr.get(i));
            re = re.next;
        }

        return head;
    }

    //     1->4->5,
//             1->3->4,
//             2->6
    public void testMethod() {
        LC21 an = new LC21();
        ListNode h1 = new ListNode(1);
        h1.next = new ListNode(4);
        h1.next.next = new ListNode(5);

        ListNode h2 = new ListNode(1);
        h2.next = new ListNode(3);
        h2.next.next = new ListNode(4);

        ListNode h3 = new ListNode(2);
        h1.next = new ListNode(6);

        ListNode[] lists = {h1, h2, h3};

        System.out.println(an.mergeKLists(lists));
    }

    public static void main(String[] args) {
        LC21 an = new LC21();
        an.testMethod();
    }
}
